package org.workplicity.android.cia.ui;

import java.util.ArrayList;

import org.workplicity.android.cia.R;
import org.workplicity.android.cia.application.ELogApplication;
import org.workplicity.android.cia.listener.ActionBarSpinnersListener;
import org.workplicity.android.cia.ui.MainActivity.MyDialogFragment;
import org.workplicity.android.cia.util.AndroidHelper;
import org.workplicity.elog.entry.ElogUser;
import org.workplicity.entry.User;
import org.workplicity.task.NetTask;
import org.workplicity.util.Helper;
import org.workplicity.worklet.WorkletContext;

import com.mongodb.BasicDBObject;
import com.mongodb.util.JSON;

import android.app.AlertDialog;
import android.app.DialogFragment;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class LoginActivity extends ELogActivity {
	
	ELogApplication app;
	
	Spinner enteredUsername;
	EditText enteredPassword;
	Button loginButton;
	
	private Integer loginStatus = 0;

	 @Override
	 public void onCreate(Bundle savedInstanceState) {
		 super.onCreate(savedInstanceState);
		 
		 app = (ELogApplication)getApplication();

		 this.setTheme(R.style.AppTheme_Light);

		 setContentView(R.layout.login);
		 
		 // run sequence to do initial login and get available usernames
		 InitialLogin initLogin = new InitialLogin();
		 initLogin.execute();

		 // User list spinner
		 refresh();

		 loginButton = (Button)findViewById(R.id.loginSubmit);
			
			
		 loginButton.setOnClickListener(new View.OnClickListener() {
				
			 public void onClick(View v) {
				 // get the username and password
				 enteredUsername = (Spinner)findViewById(R.id.userSpinner);
				 enteredPassword = (EditText)findViewById(R.id.loginPassword);
				 
				 if (enteredPassword != null && enteredUsername != null) {
					 // kick of the thread to try to log in with user credentials
					 Login myLogin = new Login();
					 myLogin.execute(enteredUsername.getSelectedItem().toString(), enteredPassword.getText().toString(), LoginActivity.this.app.getContext());
				 }
			 }
		 });
		 
	 }
	 

	 /**
	  * Called after query to db has returned a verdict on users login info.
	  * Checks to see if login info is correct and acts accordingly.
	  */
	 private void login() {
		 if(this.getLoginStatus() == 1) {
			 try{
				 
				 // get the user and store in app.currentUser
				 // TODO I am temp forcing admin to be the logged in user
				 app.setLoggedInUser(app.getAllUsers().get(0));
				 
				 // go to the main screen
				 Intent intent = new Intent(LoginActivity.this, MainActivity.class);
				 startActivityForResult(intent, 1);
			 }
			 catch(Exception e) {
				 // login failed!
				 new AlertDialog.Builder(LoginActivity.this)
		            .setIcon(android.R.drawable.ic_dialog_alert)
		            .setTitle(getString(R.string.error))
		            .setMessage(getString(R.string.databaseconnection))
		            .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

		                @Override
		                public void onClick(DialogInterface dialog, int which) {

		                    //Stop the activity
		                    LoginActivity.this.finish();    
		                }

		            })
		            .show();
			 }
		 }
		 else if (this.getLoginStatus() == 2) {
			 // login failed
			 new AlertDialog.Builder(LoginActivity.this)
	            .setIcon(android.R.drawable.ic_dialog_alert)
	            .setTitle(getString(R.string.error))
	            .setMessage(getString(R.string.loginerror))
	            .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

	                @Override
	                public void onClick(DialogInterface dialog, int which) {

	                    //Stop the activity
	                      
	                }

	            })
	            .show();
		 }
	 }
	 
	 /**
	  * Refreshs the view, called mainly to update the list of available usernames in the dropdown.
	  */
	 public void refresh() {
		 
		 Spinner userSpinner = (Spinner)findViewById(R.id.userSpinner);
		 ArrayAdapter<String> userAdapter;
		 
		 try {
			 userAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, app.getAllUsersUsernames());
		 }
		 catch(Exception e) {
			 String[] tempUser = new String[1];
			 tempUser[0] = "Loading...";
			 userAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, tempUser);
		 }
	 
		 userAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);    
		 userSpinner.setAdapter(userAdapter);
		 userSpinner.setOnItemSelectedListener(new ActionBarSpinnersListener());
	 }
	 
	 public void setLoginStatus(Integer loginStatus) {
		 this.loginStatus = loginStatus;
	 }

	 public Integer getLoginStatus() {
		 return loginStatus;
	 }

	/**
	 * Asycthread that handles the network transaction to handle initial admin login.  This 
	 * is required to get the userlist from the database.
	 * @author brian.gormanly
	 *
	 */
	class InitialLogin extends AsyncTask<Object, Void, Integer> {

		@Override
		protected Integer doInBackground(Object... arg0) {
			// create success member
	        Integer success = 0;
	        
			try {
		        
		        // cast the variables comming in
		        String username = "admin";
		        String password = "gaze11e";
		        WorkletContext context = (WorkletContext)LoginActivity.this.app.getContext();
		        
		        if (!Helper.login(username, password, context)) {
		        	android.util.Log.d("alarm", "Failed Login");
		        	success = 0;
		        }
		        else {
		        	android.util.Log.d("alarm", "************Login Success****************");
		        	success = 1;
		        }
	        }
	        catch(Exception e) {
	        	success = 0;
	        }
	        
	        return success;
		}
		
		protected void onPostExecute(Integer success) {
	        if(success > 0) {
	        	// do the query to get all the users
	        	LoginNameQuery loginNames = new LoginNameQuery();
	        	String criteria = JSON.serialize(new BasicDBObject("entry.id",new BasicDBObject("$gte",0)));
	    	
	        	loginNames.execute(NetTask.REPOS_ACCOUNTS, criteria, app.getContext());
	        	
	        }
	        else {
	        	android.util.Log.d("alarm", "%%%%%%%%%HELP%%%%%%%%%");

	        }
	        
	        android.util.Log.d("alarm", "!All done2222222!");
		}	
	}
	
	/**
	 * AsyncThread that handles the users login to the database.
	 * @author brian.gormanly
	 *
	 */
	class Login extends AsyncTask<Object, Void, Integer> {

		@Override
		protected Integer doInBackground(Object... arg0) {
			// create success member
	        Integer success = 0;
	        
			try {
		        
		        // cast the variables comming in
		        String username = arg0[0].toString();
		        String password = arg0[1].toString();
		        WorkletContext context = (WorkletContext)arg0[2];
		        
		        android.util.Log.d("alarm", "Start Login");
		        
		        if (!Helper.login(username, password, context)) {
		        	android.util.Log.d("alarm", "Failed Login");
		        	
		        	success = 0;
		        }
		        else {
		        	android.util.Log.d("alarm", "************Login Success****************");
		        	
		        	success = 1;
		        }
		       
	        }
	        catch(Exception e) {
	        	success = 0;
	        }
	        
	        return success;
		}
		
		protected void onPostExecute(Integer success) {
	        if(success > 0) {
	        	LoginActivity.this.setLoginStatus(1);
	
	        	
	        }
	        else {
	        	LoginActivity.this.setLoginStatus(2);
	        	android.util.Log.d("alarm", "%%%%%%%%%HELP%%%%%%%%%");
	        	
	        }
	        
	        android.util.Log.d("alarm", "!All done2222222!");
	        
	        // check the logon
	        login();
	    }
		
		
	}
	 
	/**
	 * AsyncThread that handles the query to get all the available usernames from the 
	 * database once the admin account is successfully logged in.
	 * @author brian.gormanly
	 *
	 */
	class LoginNameQuery extends AsyncTask<Object, Integer, ArrayList<ElogUser>> {

		@Override
		protected ArrayList<ElogUser> doInBackground(Object... arg0) {
			try {
				Looper.myLooper().prepare();
			}
			catch(Exception e) {
				// Looper only needs to be created if the thread is new, if reusing the thread we end up here
			}
			
			try {
		        
		        // cast the variables comming in
				String repos = arg0[0].toString();
		        String criteria = arg0[1].toString();
		        WorkletContext context = (WorkletContext)arg0[2];
		        
		        ArrayList<ElogUser> users = Helper.query(repos, criteria, context);
		        	
		       
		        return users;
		       
		    }
		    catch(Exception e) {
		    	e.printStackTrace();
		    	return null;
		    }
		}
		
		protected void onPostExecute(ArrayList<ElogUser> users) {
		    
		    
		    try {
		    	
		    	for(ElogUser user : users) {
		        	android.util.Log.d("alarm", "!!!!!!!!!!!User: " + user.getFirstName() + " " + user.getLastName());
		        }
		    
		        app.setAllUsers(users);
		        
		        // refresh the view
		        refresh();
		        
		        android.util.Log.d("alarm", "^^^^^^^^^^^^^^^^^!All done!^^^^^^^^^^^^^^^^^^^^^^^^");
		        
		        
		        
		    }
		    catch(Exception e) {
		    	new AlertDialog.Builder(LoginActivity.this)
		        .setIcon(android.R.drawable.ic_dialog_alert)
		        .setTitle("Error!")
		        .setMessage("Not able to connect to the CIAELog database! The application will close.")
		        .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
		
		            @Override
		            public void onClick(DialogInterface dialog, int which) {
		
		                //Stop the activity
		                LoginActivity.this.finish();    
		            }
		
		        })
		        .show();
		    }
		    
		    
		}

	 }
}
